#!/bin/bash

# NOTE: this script should be execute at path where 'test_employee.txt' is held.

# -- nromal printing -- 

# - using sed 'p' command, sed can print the current pattern space.
# the reason that 'p' command is here since 'print current pattern space' is already in sed execute circle
# is controls what is printed to stdout. we often using 'p' to do filtering the input.
# we usually combine -n option to 'p' togeter to suppress the defualt printing.

sed 'p' test_employee.txt # every line will be printed twice, since implicit printing is working.
echo -e '\n' 
sed -n 'p' test_employee.txt # every line will be pritned only once.
echo -e '\n' 


# -- specifying address range -- 
# if you don't specify an address range before the sed command, by defualt, sed matches all the lines.

# - give a number before 'p' command with a ' ' in between, sed will print specified line.
sed -n '2 p' test_employee.txt # only prints the second line of given file
echo -e '\n'

# - give a range seperate by ',' before 'p' command , sed will print lines in given range.
sed -n '2,4 p' test_employee.txt # prints line 2 to line 4 of given file
echo -e '\n'

# - '$' sign represents the last line of given file
sed -n '3,$ p' test_employee.txt # print from line 3 to the end of file.
echo -e '\n'


# -- Modify address range -- 
# - use ',' to specify address range : n,m indicates n through m 
# - use '+' togeter with ',' specify the number of lines to be printed: n,+m indicates n through n+m.
# - use '~' specify skipping lines with given number: n~m start at n pick up every mth line from there.
sed -n '1,+2 p' test_employee.txt # prints line 1, 2, 3
echo -e '\n'

sed -n '1~2 p' test_employee.txt # starts with line 1, prints every 2 line, prints 1, 3, 5 line
echo -e '\n'

sed -n '1~3 p' test_employee.txt # prints 1, 4
echo -e '\n'


# -- Pattern Matching --
# - use '/pattern/' to matching the lines whitch contains 'pattern'
sed -n '/Jane/ p' test_employee.txt # prints 105
echo -e '\n'

# - use '/pattern/,n' to print lines starting from 1st match of 'pattern' until reach line n
sed -n '/John/,4 p' test_employee.txt # prints 101,102,103,104 
echo -e '\n'
# NOTE: if there were no matchs for 'pattern' in 1st n lines, it would print lines that 
# match 'pattern' after the nth lines
sed -n '/Raj/,2 p' test_employee.txt # no Raj at line 1 & 2, so it prints 103
echo -e '\n'

# - use '/pattern1/,/pattern2/' to print line matching 'pattern1' until the line matching 'pattern2'
sed -n '/Raj/,/jane/ p' test_employee.txt # prints 103, 104, 105
echo -e '\n'

# - use '/pattern/, +n' prints the line matching 'pattern' and 2 lines immediate after that.
sed -n '/Raj/,+2 p' test_employee.txt #prints 103, 104, 105
